<?php
namespace app\open\model;
use app\common\model\OpenBase;

class UserAuth extends OpenBase {
	protected $tableName = 'user_auth'; //user信息表
	//定义字段信息
	protected $fields = [
		0 => 'id',
		1 => 'uid',
		2 => 'ak',
		3 => 'ck',
		4 => 'create_time',
		'_pk' => 'id',
	];
	//设置自动填充的数据
	protected $auto = [];
	//初始化方法
	protected function _initialize() {}
	/**
	 * @name 公共的api请求验证方法(需要登陆后才能请求的api)
	 * @access public
	 * @param array $data 授权信息
	 *  param : string auth_accesskey
	 *  param : string auth_secretkey
	 * @return array 检验结果  code为00000时通过
	 */
	public function checkAuthForApi($ak = '') {
	    if(!$ak) return false;
        $data = [
            'ak' => substr($ak,0,16),
            'ck' => substr($ak,16)
        ];
		if (!$data['ak'] || !$data['ck']) {
			$this->error = '参数不完整';
			return false;
		}
		$auth = $this->field(['uid'])->where($data)->find();
		if ($auth) {
			return $auth['uid'];
		}
		$this->error = '非法访问';
		return false;
	}
	/**
	 * @name 取得权限数据
	 * @access protected
	 * @param int or string $uid 用户uid
	 * @return array 权限数据
	 */
	public function getAuthdata($uid = '', $create = false) {
		if (!$uid) {
			return array();
		}
		//创建授权key
		return self::_createAuth($uid, $create);
	}

	/**
	 * @name 创建api权限数据
	 * @access protected
	 * @param int $uid 用户uid
	 * @return array 权限数据
	 */
	protected function _createAuth($uid = 0, $create = false) {
		if (!$uid) {
			return [];
		}
		//查询是否有权限数据
		$auth = $this->where('uid=' . $uid)->field(['id', 'ak', 'ck'])->find();
		if (!$auth || $create === true) {
			$key = self::_createCode(4);
			$apiKey = md5($key . $uid);
			$auth['ak'] = $key.substr($apiKey, 4, 12);
			$auth['ck'] = substr($apiKey, 20).$key;
			$auth['uid'] = $uid;
			$auth['create_time'] = NOW_TIME;
			$action = $auth['id'] ? 'save' : 'add';
			$this->$action($auth);
		} else {
			$this->where('uid=' . $uid)->setField('create_time', NOW_TIME);
		}
		return ['ak' => $auth['ak'].$auth['ck']];
	}
	/**
	 * @name 更新授权信息
	 * @access public
	 * @param string $ak 授权ak
	 * @param string $ck 授权ck
	 * @return array 更新授权结果 如果成功,返回用户的信息
	 */
	public function updateAuth($ak = '', $ck = '') {
		if ($ak && $ck) {
			$map['ak'] = $ak;
			$map['ck'] = $ck;
			$uid = $this->where($map)->getField('uid');
			if (!$uid) {
				return getApiErrorCode('00500');
			}
			//更新授权
			$this->where($map)->setField('create_time', NOW_TIME);
			return true;
		}
		return getApiErrorCode('00500');
	}
	/**
	 * @name 清理授权
	 */
	public function clearAuth($uid = 0) {
		if ($uid) {
			return $this->where('uid=' . (int) $uid)->delete() ? true : false;
		}
		return true;
	}
}